<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';

// 直接复用渲染组件
import DevicePreviewRender from './DevicePreviewRender.vue';

/* ───── 路由参数 ───── */
const route = useRoute();
const deviceId = ref((route.params.deviceId as string) || '');

/* ───── 组件状态 ───── */
const config = ref<any>(null);
const loading = ref(true);
const error = ref('');
const selectedLayerId = ref<null | string>(null); // 预览不可编辑，占位即可

/* ───── 拉取并解析设备配置 ───── */
async function loadConfig() {
  loading.value = true;
  error.value = '';

  try {
    const resp = await fetch(`/api/jx-device/Device/${deviceId.value}`);
    const json = await resp.json();

    if (json.code === 200 && json.data) {
      /* deviceJson 被双重 stringify，先拆外层再 parse 内层 */
      let parsed: any = {};
      try {
        parsed = JSON.parse(json.data.deviceJson);
        console.log('deviceJson', parsed);
      } catch {
        console.warn('deviceJson 解析失败，使用空配置');
      }

      /* 兜底：保证关键字段是数组，避免渲染时报错 */
      parsed.layers = Array.isArray(parsed.layers) ? parsed.layers : [];
      parsed.materialsTree = Array.isArray(parsed.materialsTree)
        ? parsed.materialsTree
        : [];

      /* 设定默认宽高，避免 0 / undefined */
      config.value = {
        deviceId: deviceId.value,
        width: parsed.width || 900,
        height: parsed.height || 600,
        ...parsed,
      };
    } else {
      error.value = json.msg || '未找到设备配置';
    }
  } catch (e) {
    console.error(e);
    error.value = '加载失败';
  }

  loading.value = false;
}

onMounted(loadConfig);
</script>

<template>
  <div class="device-preview-page relative h-full w-full bg-[#161a21]">
    <!-- 加载状态 -->
    <div
      v-if="loading"
      class="flex h-full items-center justify-center text-gray-400"
    >
      加载中…
    </div>

    <!-- 错误提示 -->
    <div
      v-else-if="error"
      class="flex h-full items-center justify-center text-red-400"
    >
      {{ error }}
    </div>

    <!-- 正常渲染 -->
    <div v-else>
      <DevicePreviewRender :config="config" />
    </div>

    <!-- 返回编辑按钮 -->
    <div class="absolute left-4 top-4 z-50">
      <router-link
        :to="{ name: 'DeviceEditor', params: { deviceId } }"
        class="rounded border border-[#3ae0ff] bg-[#2a69d7] px-3 py-1 text-white hover:bg-[#154c8a]"
      >
        返回编辑
      </router-link>
    </div>
  </div>
</template>

<style scoped>
.device-preview-page {
  min-height: 100vh;
}
</style>
